package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelReadVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationPeriodVO;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.eduPrivateAppointStudent.EduPrivateAppointStudentKeyVO;
import com.jwsoft.manager.common.vo.eduPrivateAppointStudent.EduPrivateAppointStudentQueryVO;
import com.jwsoft.manager.common.vo.eduPrivateAppointStudent.EduPrivateAppointStudentVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduPrivateAppointStudent;
import com.jwsoft.manager.core.dao.service.EduPrivateAppointStudentService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.integration.EduPrivateAppointStudentIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 民办直升班名单表业务实现类
 *
 * @author wangtao
 * @since 2022-12-16
 */
@ApiService(funcCode = "eduPrivateAppointStudent", title = "民办直升班名单表")
public class EduPrivateAppointStudentIntegrationImpl implements EduPrivateAppointStudentIntegration {

    @Autowired
    public EduPrivateAppointStudentService eduPrivateAppointStudentService;

    @Autowired
    public EduStudentEnrollPreIntegrationImpl eduStudentEnrollPreIntegration;

    @Autowired
    ExcelCommonHelper excelCommonHelper;

    @Resource
    private ApiContainer apiContainer;

    @Resource
    OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    OperationCacheIntegration operationCacheIntegration;

    @Autowired
    EduSchoolService eduSchoolService;

    @Autowired
    private DictIntegration dictIntegration;

    @Autowired
    RedisHelper redisHelper;


    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0001", title = "民办直升班名单表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduPrivateAppointStudentVO> getList(EduPrivateAppointStudentQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (CollectionUtils.isEmpty(areaCodeList)){
            throw new AppException("必须传入行政区划");
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduPrivateAppointStudent> privateAppointStudentQueryWrapper = new QueryWrapper<>();
        if (vo.getYear() == null){
            Integer year = operationCacheIntegration.getPeriodYear().getYear();
            vo.setYear(year);
        }
        privateAppointStudentQueryWrapper
                .lambda()
                .eq(
                        !ObjectUtils.isEmpty(vo.getSchoolId()),
                        EduPrivateAppointStudent::getSchoolId,
                        vo.getSchoolId())
                .eq(
                        !ObjectUtils.isEmpty(vo.getFullName()),
                        EduPrivateAppointStudent::getFullName,
                        vo.getFullName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getIdcard()),
                        EduPrivateAppointStudent::getIdcard,
                        vo.getIdcard())
                .in(EduPrivateAppointStudent::getAreaCode,areaCodeList)
                .eq(!ObjectUtils.isEmpty(vo.getYear()), EduPrivateAppointStudent::getYear, vo.getYear());
        List<EduPrivateAppointStudentVO> list = eduPrivateAppointStudentService.queryPromotionlist(privateAppointStudentQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduPrivateAppointStudentVO> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduPrivateAppointStudentVO> resultList = Convert.toList(EduPrivateAppointStudentVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0002", title = "民办直升班名单表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduPrivateAppointStudentVO getById(EduPrivateAppointStudentKeyVO vo) {
        EduPrivateAppointStudent entity = eduPrivateAppointStudentService.getById(vo.getPrivateAppointStudentId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduPrivateAppointStudentVO result = Convert.convert(EduPrivateAppointStudentVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0003", title = "民办直升班名单表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduPrivateAppointStudentVO vo) {
        //主键为空为新增校验

        if (StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("未选择行政区域！");
        }

        if (StringUtils.isBlank(vo.getSchoolId())){
            throw new AppException("未选择目标学校！");
        }




        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0004", title = "民办直升班名单表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduPrivateAppointStudent0004",
            operationName = "民办直升班名单表新增",
            dataType = "privateAppointStudentId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduPrivateAppointStudentVO add(EduPrivateAppointStudentVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        QueryWrapper<EduPrivateAppointStudent> privateAppointStudentQueryWrapper =
                new QueryWrapper<>();
        privateAppointStudentQueryWrapper
                .lambda()
                .eq(EduPrivateAppointStudent::getIdcard, vo.getIdcard())
                .eq(EduPrivateAppointStudent::getYear, vo.getYear());
        long count = eduPrivateAppointStudentService.count(privateAppointStudentQueryWrapper);
        if (count > 0) {
            throw new AppException("该学生该年度已存在数据！");
        }
        EduPrivateAppointStudent privateAppointStudent = new EduPrivateAppointStudent();
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("统筹区不能为空！");
        }
        privateAppointStudent.setAreaCode(vo.getAreaCode());
        privateAppointStudent.setIdcard(StringUtils.upperCase(vo.getIdcard()));
        privateAppointStudent.setFullName(vo.getFullName());
        privateAppointStudent.setSchoolId(vo.getSchoolId());
        privateAppointStudent.setStatus(BoolEnum.TRUE.getType());
        privateAppointStudent.setRemark(vo.getRemark());
        privateAppointStudent.setPrivateAppointStudentId(IdUtil.simpleUUID());
        int year = 0;
        OperationCurVO curVO = new OperationCurVO();
        curVO.setOperating("XN");
        OperationPeriodVO operationPeriodVO =
                operationPeriodIntegration.getCurrentByOperating(curVO);
        if (operationPeriodVO != null) {
            year = operationPeriodVO.getPeriodYear();
        } else {
            year = DateUtil.thisYear();
        }
        privateAppointStudent.setYear(year);
        eduPrivateAppointStudentService.save(privateAppointStudent);
        //将主键设置回vo使操作日志可以取到
        vo.setPrivateAppointStudentId(privateAppointStudent.getPrivateAppointStudentId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0005", title = "民办直升班名单表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduPrivateAppointStudent0005",
            operationName = "民办直升班名单表修改",
            dataType = "privateAppointStudentId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduPrivateAppointStudentVO edit(EduPrivateAppointStudentVO vo) {
        if (ObjectUtils.isEmpty(vo.getPrivateAppointStudentId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }

        Integer year = operationCacheIntegration.getPeriodYear().getYear();
        if (!year.equals(vo.getYear())){
            throw new AppException("只能操作当前年度的信息!");
        }
        EduPrivateAppointStudent privateAppointStudent = eduPrivateAppointStudentService.getById(vo.getPrivateAppointStudentId());
        if (!ObjectUtils.isEmpty(privateAppointStudent)) {
            QueryWrapper<EduPrivateAppointStudent> privateAppointStudentQueryWrapper =
                    new QueryWrapper<>();
            privateAppointStudentQueryWrapper
                    .lambda()
                    .eq(EduPrivateAppointStudent::getIdcard, vo.getIdcard())
                    .eq(EduPrivateAppointStudent::getYear, vo.getYear())
                    .ne(
                            EduPrivateAppointStudent::getPrivateAppointStudentId,
                            vo.getPrivateAppointStudentId());
            long count = eduPrivateAppointStudentService.count(privateAppointStudentQueryWrapper);
            if (count > 0) {
                throw new AppException("该学生该年度已存在数据！");
            }
            BeanUtil.copyProperties(
                    vo, privateAppointStudent, CopyOptions.create().ignoreNullValue());
            eduPrivateAppointStudentService.saveOrUpdate(privateAppointStudent);
        } else {
            throw new AppException("查询不到e类信息");
        }
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0006", title = "民办直升班名单表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduPrivateAppointStudent0006",
            operationName = "民办直升班名单表删除",
            dataType = "privateAppointStudentId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduPrivateAppointStudentKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getPrivateAppointStudentId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduPrivateAppointStudent entity = eduPrivateAppointStudentService.getById(vo.getPrivateAppointStudentId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }

        Integer year = operationCacheIntegration.getPeriodYear().getYear();
        if (!year.equals(entity.getYear())){
            throw new AppException("只能操作当前年度的信息!");
        }
        eduPrivateAppointStudentService.removeById(vo.getPrivateAppointStudentId());
    }

    @Override
    @OpApi(funcCode = "eduPrivateAppointStudent0007", title = "民办直升班名单上传", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduPrivateAppointStudent0007",
            operationName = "民办直升班名单上传",
            dataType = "privateAppointStudentId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public ExcelReadVO readExcel(ExcelVO vo, MultipartFile file,EduPrivateAppointStudentVO appVo) {

        ExcelReadVO excelReadVO = new ExcelReadVO();
        excelReadVO.setCount(0);
        ExcelModelVO excelModelVO = eduStudentEnrollPreIntegration.getModel(vo);
        InputStream in = null;
        String schoolId = appVo.getSchoolId();
        try {
            in = file.getInputStream();
            // File file2 = new File("C:\\Users\\Administrator\\Desktop\\工作簿1.xlsx");
            // in = new FileInputStream(file);
            if (StringUtils.isBlank(excelModelVO.getReadClass())) {
                List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);

                List<Map<String, Object>> successList = new ArrayList<>();
                List<Map<String, Object>> errorList = new ArrayList<>();
                List<String> idcardList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    EduPrivateAppointStudentVO studentVO = JSON.parseObject(JSON.toJSONString(map), EduPrivateAppointStudentVO.class);
                    if (studentVO.getIdcard() == null || studentVO.getFullName() == null) {
                        throw new AppException("模板有误!");
                    }
                    String remarks = "";
                    boolean flag = false;

                    if (StringUtils.isBlank(studentVO.getIdcard())) {
                        remarks += "学生证件号码不能为空！";
                        flag = true;
                    } else {
                        studentVO.setIdcard(studentVO.getIdcard().trim().toUpperCase());
                    }

                    if (ObjectUtils.isEmpty(studentVO.getFullName())) {
                        remarks += ("学生姓名不能为空！");
                        flag = true;
                    } else {
                        studentVO.setFullName(
                                Validator.isChinese(studentVO.getFullName())
                                        ? studentVO.getFullName().replace(" ", "").trim()
                                        : studentVO.getFullName().trim());
                    }
                    // 校验数据是否存在
                    int year = 0;
                    OperationCurVO curVO = new OperationCurVO();
                    curVO.setOperating("XN");
                    OperationPeriodVO operationPeriodVO =
                            operationPeriodIntegration.getCurrentByOperating(curVO);
                    if (operationPeriodVO != null) {
                        year = operationPeriodVO.getPeriodYear();
                    } else {
                        year = DateUtil.thisYear();
                    }
                    QueryWrapper<EduPrivateAppointStudent> appointStudentQueryWrapper =
                            new QueryWrapper<>();
                    appointStudentQueryWrapper
                            .lambda()
                            .eq(EduPrivateAppointStudent::getIdcard, studentVO.getIdcard())
                            .eq(EduPrivateAppointStudent::getYear, year);
                    long count = eduPrivateAppointStudentService.count(appointStudentQueryWrapper);
                    if (count > 0) {
                        flag = true;
                        remarks = "该学生证件号码信息已存在";
                    }
                    if (flag) {
                        studentVO.setRemark(remarks);
                        studentVO.setYear(year);
                        errorList.add(JSON.parseObject(JSON.toJSONString(studentVO), Map.class));
                    } else {
                        // 保存表信息
                        EduPrivateAppointStudent appointStudent = new EduPrivateAppointStudent();
                        appointStudent.setIdcard(StringUtils.upperCase(studentVO.getIdcard()));
                        appointStudent.setFullName(studentVO.getFullName());
                        appointStudent.setSchoolId(appVo.getSchoolId());
                        appointStudent.setPrivateAppointStudentId(IdUtil.simpleUUID());
                        appointStudent.setYear(year);
                        appointStudent.setStatus(BoolEnum.TRUE.getType());
                        if(ObjectUtils.isEmpty(appVo.getAreaCode())){
                            appVo.setAreaCode(SessionUtil.getAreaCode());
                        }
                        appointStudent.setAreaCode(appVo.getAreaCode());
                        eduPrivateAppointStudentService.save(appointStudent);
                        studentVO.setPrivateAppointStudentId(appointStudent.getPrivateAppointStudentId());
                        studentVO.setYear(year);
                        EduSchoolVO eduSchool = eduSchoolService.getDetail(schoolId);
                        if(eduSchool!=null){
                            studentVO.setSchoolName(eduSchool.getSchoolName());
                        }
                        successList.add(JSON.parseObject(JSON.toJSONString(studentVO), Map.class));
                    }

                }

                excelReadVO.setCount(successList.size() + errorList.size());
                excelReadVO.setSuccessCount(successList.size());
                excelReadVO.setSuccessList(successList);
                excelReadVO.setErrorList(errorList);
                excelReadVO.setErrorCount(errorList.size());




            }else {
                // 使用funcCode读取
                //本地接口
                ApiModel apiModel = apiContainer.get(excelModelVO.getReadClass());
                if (apiModel != null) {
                    Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                    if (null != bean) {
                        Object result = apiModel.getMethod().invoke(bean, vo, file);
                        return (ExcelReadVO) result;
                    }
                }
                //todo 微服务接口
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (IOException e) {
            throw new AppException("读取文件异常:" + e.getMessage());
        } catch (IllegalAccessException e) {
            throw new AppException("调用自定义读取服务异常:" + e.getMessage());
        } catch (InvocationTargetException e) {
            throw new AppException("调用自定义读取服务异常:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return excelReadVO;
    }



}
